package com.mycat.dfs;

import org.csource.fastdfs.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * @author roger.
 * @email luojie@yzworld.cn
 * @date 2016/10/11
 */
public class UploadThread implements Runnable {

    @Override
    public void run() {
        for (int i = 0; i < 1; i++) {
            File file = new File("C:\\Users\\Public\\Pictures\\Sample Pictures\\1.jpg");
            try {

                ClientGlobal.setG_connect_timeout(1000);
                ClientGlobal.setG_charset("UTF-8");
                ClientGlobal.setG_network_timeout(6000);
                ClientGlobal.setG_secret_key("FastDFS1234567890");

//                InetAddress addr = InetAddress.getByName("192.168.2.187");
                InetAddress addr = InetAddress.getByName("119.4.210.142");
                InetSocketAddress tracker_servers = new InetSocketAddress(addr, 22122);
                InetSocketAddress[] tracker_servers_array = new InetSocketAddress[1];
                tracker_servers_array[0] = tracker_servers;

                ClientGlobal.setG_tracker_group(new TrackerGroup(tracker_servers_array));
                ClientGlobal.setG_tracker_http_port(80);
                ClientGlobal.setG_anti_steal_token(false);

                TrackerClient tracker = new TrackerClient();
                TrackerServer trackerServer = tracker.getConnection();
                StorageServer storageServer = null;
                StorageClient storageClient = new StorageClient(trackerServer, storageServer);

                ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
                byte[] buff = new byte[100];
                int rc = 0;
                InputStream input = new FileInputStream(file);
                while ((rc = input.read(buff, 0, 100)) > 0) {
                    swapStream.write(buff, 0, rc);
                }
                byte[] in2b = swapStream.toByteArray();


                String[] fileIds = storageClient.upload_file(in2b, "jpg", null);
                if (fileIds != null) {
                    String str = fileIds[0] + "/" + fileIds[1];
                    System.out.println(str);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
